package com.ruicar.afs.cloud.apply.pre.loan.mq.receiver;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOprRecord;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOprRecordService;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ApproveSubmitInfo;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CaseUrgentDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ApplyUrgentDealProcessor implements AfsMqBizProcessor<ApproveSubmitInfo> {
    private final ApplyOprRecordService oprRecordService;

    @Override
    public boolean processMessage(ApproveSubmitInfo entity) throws Exception {
        //加急
        if (ObjectUtil.isNotNull(entity.getCaseUrgentDto())) {
            if (entity.getCaseUrgentDto().getIsSuccess().equals(WhetherEnum.YES.getCode())
                    && StringUtil.isNotEmpty(entity.getCaseUrgentDto().getApplyNo())) {
                this.urgentSuccessMessage(entity.getCaseUrgentDto());
            } else if (entity.getCaseUrgentDto().getIsSuccess().equals(WhetherEnum.NO.getCode())
                    && StringUtil.isNotEmpty(entity.getCaseUrgentDto().getApplyNo())) {
                this.urgentFailedMessage(entity.getCaseUrgentDto());
            }
        }
        return true;
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_POS_APPLY_CASE_CTM_TURN_URGENT;
    }

    @Override
    public boolean reQueueOnFail() {
        return false;
    }

    /**
     * 加急成功
     *
     * @param entity
     */
    public void urgentSuccessMessage(CaseUrgentDto entity) {
        log.info("--申请编号:" + entity.getApplyNo() + "，信审接收加急报文成功");
    }

    /**
     * 加急失败,删除加急数据
     *
     * @param entity
     */
    public void urgentFailedMessage(CaseUrgentDto entity) {
        log.info("--申请编号:" + entity.getApplyNo() + "，信审接收加急报文失败");
        ApplyOprRecord applyOprRecord = this.oprRecordService.getOne(Wrappers.<ApplyOprRecord>query().lambda()
                .eq(StringUtil.isNotEmpty(entity.getApplyNo()), ApplyOprRecord::getApplyNo, entity.getApplyNo())
                .eq(ApplyOprRecord::getApplyType, OrderOprType.RECONSIDER).last("LIMIT 1"));
        //todo 更新每月可加急次数
        this.oprRecordService.removeById(applyOprRecord);
    }
}
